from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from .serializers import OrderPaySerializer
from utils.common_response import APIResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from libs.ali_pay import alipay
from order.models import Order
from utils.loggers import log_uru
import json


class OrderPayView(GenericViewSet):
    # 必须登录才能访问：认证类  权限类
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    # 校验--》生成支付链接--》生成订单--》序列化类的validate中
    serializer_class = OrderPaySerializer

    def create(self, request, *args, **kwargs):
        # 将当前登录用户对象传入
        serializer = self.get_serializer(data=request.data, context={'user': request.user})
        serializer.is_valid(raise_exception=True)
        # 保存订单
        serializer.save()
        # 获取订单链接
        pay_url = serializer.context.get('pay_url')
        return APIResponse(pay_url=pay_url)


class OrderSuccessView(APIView):
    def get(self, request, *args, **kwargs):
        out_trade_no = request.query_params.get('out_trade_no')
        order = Order.objects.filter(out_trade_no=out_trade_no, order_status=1).first()
        if order:  # 说明支付宝的post回调回来了，修改了订单状态
            return APIResponse(msg='支付成功，请去学习把')
        else:
            return APIResponse(code=101, msg='暂未收到您的付款，请稍后刷新再试')

    def post(self, request, *args, **kwargs):
        result_data = request.data.dict()  # 把request.data  ---> 转成字典格式
        log_uru.error(f'支付宝回调的数据：{json.dumps(result_data)}')
        try:
            out_trade_no = result_data.get('out_trade_no')
            trade_no = result_data.get('trade_no')
            signature = result_data.pop('sign')
            pay_time = result_data.get('notify_time')
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1, trade_no=trade_no,
                                                                       pay_time=pay_time)
                # 完成日志记录
                log_uru.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                log_uru.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')
